const crypto = require("crypto");
const express = require('express');
let router = express.Router();
const sql = require('../../sql/sqlConfig');

router.post('/', function (req, res, next) {
    let {email,password,code} = req.body;

    if(!req.session[email]) return res.send({errCode:9,message:'请先获取验证码！'});
    if(code!=req.session[email][0]) return res.send({errCode:9,message:'验证码错误！'});

    let option = "select `id` from `user` where `email`='"+email+"'";
    sql.query(option, function (err, rows) {
        if (err) return res.send({errCode: -9999, message: '操作数据库失败' + err});
        if (rows.length != 0) return res.send({errCode: 9, message: '该邮箱已经注册过啦'});

        let md5 = crypto.createHash("md5");
        let newPas = md5.update(password).digest("hex");
        let insertSql = "insert into `user`(`is_admin`,`email`,`password`) values(0,'" + email + "','" + newPas + "')";
        sql.query(insertSql, function (err, rows) {
            if (err) return res.send({errCode: -9999, message: '操作数据库失败' + err});
            return res.send({errCode:0,message:'注册成功!'})
        })
    })
});

module.exports = router;
